package com.netcracker.studies;

import Bank.MD5Utils;
import Bank.User;
import Beans.AuthorizationBean;
import Beans.AuthorizationBeanInterface;
import DBConnection.DBAPI;
import DBConnection.DBObject;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Objects;


@WebServlet(name = "ChangePasswordServlet")
public class ChangePasswordServlet extends BaseServlet {
    private static final Logger log = Logger.getLogger(User.class);
    protected void handlePostRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/plain; charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession(true);
        AuthorizationBeanInterface a = (AuthorizationBeanInterface) session.getAttribute("UserBean");
        if ((request.getParameter("password").isEmpty()) || (request.getParameter("password1").isEmpty())){
            response.getWriter().write("Пароль не может быть пустым");
            return;
        }
        if ((request.getParameter("password").length() < 3)){
            response.getWriter().write("Пароль должен быть длиннее 3х символов");
            return;
        }
        if (!Objects.equals(request.getParameter("password"), request.getParameter("password1")))
            response.getWriter().write("Пароли не совпадают");
        else {
            DBObject d1 = DBAPI.getUserByLogin("login6");
            DBAPI.updateParam(d1.getID(), new BigInteger("9000001429971012173"), MD5Utils.md5Custom(request.getParameter("password")));

            response.getWriter().write("Пароль успешно сменен ");
        }
    }

    protected void handleGetRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//
        response.setContentType("text/plain; charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        //response.getWriter().write("passchanger.jsp");
        request.getRequestDispatcher("passchanger.jsp").forward(request,response);
    }
}
